﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows8Accelerator.Core.Xaml.Controls.RichText;

namespace Windows8Accelerator.Core.Xaml.Helpers
{
    public class RichTextBlockHelper : DependencyObject
    {
        public static readonly DependencyProperty HtmlSourceProperty = DependencyProperty.RegisterAttached(
              "HtmlSource",
              typeof(string),
              typeof(RichTextBlockHelper),
              new PropertyMetadata(null, HtmlSourcePropertyChanged)
            );

        private static void HtmlSourcePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var element = (RichTextBlock)d;
            var value = (string)e.NewValue;
            if (value != null)
            {
                var richTextBlockHtmlLoader = GetRichTextBlockHtmlLoader(element);
                if (richTextBlockHtmlLoader == null)
                {
                    richTextBlockHtmlLoader = new RichTextBlockHtmlLoader();
                    SetRichTextBlockHtmlLoader(element, richTextBlockHtmlLoader);
                }
                richTextBlockHtmlLoader.Load(element, value);
            }
        }

        public static void SetHtmlSource(RichTextBlock element, string value)
        {
            element.SetValue(HtmlSourceProperty, value);           
        }

        public static string GetHtmlSource(RichTextBlock element)
        {
            return (string)element.GetValue(HtmlSourceProperty);
        }

        public static readonly DependencyProperty RichTextBlockHtmlLoaderProperty = DependencyProperty.RegisterAttached(
          "RichTextBlockHtmlLoader",
          typeof(RichTextBlockHtmlLoader),
          typeof(RichTextBlockHelper),
          new PropertyMetadata(null)
        );

        public static void SetRichTextBlockHtmlLoader(RichTextBlock element, RichTextBlockHtmlLoader value)
        {
            element.SetValue(RichTextBlockHtmlLoaderProperty, value);
        }

        public static RichTextBlockHtmlLoader GetRichTextBlockHtmlLoader(RichTextBlock element)
        {
            return (RichTextBlockHtmlLoader)element.GetValue(RichTextBlockHtmlLoaderProperty);
        }
    }
}
